package tw.zld369504.wol.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

import tw.zld369504.wol.action.DBOperationInterface;
import tw.zld369504.wol.model.Profile;

/**
 * database operation inside
 */
public class DBOperation implements DBOperationInterface {
    private Context mContext;
    private static DBOperation op;
    private DBHelper helper;
    private DBOperation(Context mContext){
        this.mContext=mContext;
        helper=new DBHelper(mContext,"profile");
    }

    public static DBOperation getInstance(Context mContext){
        if(op==null){
            op=new DBOperation(mContext);
        }
        return op;
    }

    @Override
    public void initDataBase() {
        SQLiteDatabase db=helper.getWritableDatabase();
        db.close();
    }

    @Override
    public void addRecord(Profile profile) {
        SQLiteDatabase db=helper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("profileName", profile.getProfileName());
        values.put("ip",profile.getIp());
        values.put("mac",profile.getMac());
        values.put("port",profile.getPort());
        db.insert("wol",null,values);
        db.close();
    }

    @Override
    public void deleteRecord(Profile profile) {

    }

    @Override
    public List<Profile> getAllProfileFromDb() {
        List<Profile> profileList=new ArrayList<>();
        SQLiteDatabase db=helper.getReadableDatabase();
        Cursor cursor=db.rawQuery("select * from wol",null);
        if(cursor.moveToFirst()){
            do{
                Profile nProfile=new Profile();
                nProfile.setIp(cursor.getString(cursor.getColumnIndex("ip")));
                nProfile.setMac(cursor.getString(cursor.getColumnIndex("mac")));
                nProfile.setPort(cursor.getString(cursor.getColumnIndex("port")));
                nProfile.setProfileName(cursor.getString(cursor.getColumnIndex("profileName")));
                profileList.add(nProfile);
            }while(cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return profileList;
    }
}
